package com.cy.dda.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;

import com.cy.dda.comm.constant.Constants;
import com.cy.dda.comm.exception.MsgException;
import com.cy.dda.comm.utils.CommonUtils;
import com.cy.dda.model.Result;
import com.cy.dda.model.dto.rule.ManagerLoginDTO;
import com.cy.dda.model.dto.user.UserLoginDTO;
import com.cy.dda.model.enums.SmsType;

/**
 * 控制器 BaseController
 *
 * @author: tanyilin
 * @create: 2018年10月26日 下午2:37:19
 */
public class BaseController {

	@Autowired
    protected RedisTemplate redisTemplate;
    @Autowired
    protected HttpServletRequest request;
	
	protected void state(boolean expression, String message) {
		if(!expression) {
			throw new MsgException(message);
		}
	}
	
	/**
	 * 校验错误信息
	 * 
	 * @param bindingResult
	 */
	protected void checkError(BindingResult bindingResult) {
		if(!bindingResult.hasErrors()) {
			return;
		}
		String message = bindingResult.getAllErrors().get(0).getDefaultMessage();
		throw new MsgException(message); 
	} 
	
	protected Result ok() {
		return Result.success();
	}
	
	protected Result ok(String message) {
		return Result.success(message);
	}
	
	protected Result ok(String message, Object value) {
		return Result.success(message, value);
	}
	
	protected Result fail(String message) {
		return Result.fail(message);
	}
	
	/**
	 * 获取当前登录的前台用户信息
	 * 
	 * @return
	 */
	protected UserLoginDTO getUser() {
		String token = request.getHeader("token");
		if (CommonUtils.isEmpty(token)) {
            throw new MsgException("没有发现token");
        }
		String key = Constants.USER_LOGIN_KEY.concat(token);
		UserLoginDTO userLoginDTO = (UserLoginDTO) redisTemplate.opsForValue().get(key);
        return userLoginDTO;
	}
	
	/**
	 * 获取当前登录的后台管理员账户信息
	 * 
	 * @return
	 */
	protected ManagerLoginDTO getManager() {
		String token = request.getHeader("token");
		if (CommonUtils.isEmpty(token)) {
            throw new MsgException("没有发现token");
        }
		String key = Constants.ADMIN_LOGIN_KEY.concat(token);
		ManagerLoginDTO managerLoginDTO = (ManagerLoginDTO) redisTemplate.opsForValue().get(key);
        return managerLoginDTO;
	}
	
	/**
	 * 验证手机短信验证码
	 * 
	 * @param mobile
	 * @param code
	 * @param type
	 */
	protected void checkSmsCode(String mobile, String code, SmsType smsType) {
		String key = CommonUtils.smsCodeKey(mobile, smsType);
		Object obj = redisTemplate.opsForValue().get(key);
		if(CommonUtils.isEmpty(obj)) {
			throw new MsgException("短信验证码已失效。");
		}
		
		if(!String.valueOf(obj).equals(code)) {
			throw new MsgException("短信验证码错误。");
		}
	}
	
}
